"use client"

import { Button } from "@/components/ui/button"
import { useRouter, useSearchParams } from "next/navigation"
import { useState, useEffect } from "react"

interface Event {
  id: string
  title: string
  date: string
  description: string | null
}

interface EventResult {
  eventId: string
  date: string
  score: number
  yearDiff: number
  dayDiff: number
  isSelected: boolean
}

interface GameRound {
  targetDate: string
  events: Event[]
  selectedEventId: string | null
  results: EventResult[] | null
  correctAnswerId: string | null
  score: number
}

export default function GamePlayPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const librariesParam = searchParams.get("libraries")
  
  const [currentRound, setCurrentRound] = useState(0)
  const [rounds, setRounds] = useState<GameRound[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string>("")
  const [gameOver, setGameOver] = useState(false)
  const [totalScore, setTotalScore] = useState(0)
  const [gameStarted, setGameStarted] = useState(false)

  useEffect(() => {
    if (!librariesParam || gameStarted) return
    
    const libraries = librariesParam.split(",")
    if (libraries.length === 0) {
      router.push("/game")
      return
    }
    
    startNewGame(libraries)
    setGameStarted(true)
  }, [librariesParam, gameStarted])

  const startNewGame = async (libraries: string[]) => {
    setLoading(true)
    setError("")
    try {
      const response = await fetch("/api/game/start", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ libraries }),
      })

      if (!response.ok) throw new Error("开始游戏失败")
      
      const data = await response.json()
      setRounds(data.rounds)
      setCurrentRound(0)
      setGameOver(false)
      setTotalScore(0)
    } catch (err) {
      setError("无法开始游戏")
    } finally {
      setLoading(false)
    }
  }

  const selectEvent = async (eventId: string) => {
    if (gameOver || rounds[currentRound].selectedEventId) return

    const updatedRounds = [...rounds]
    updatedRounds[currentRound].selectedEventId = eventId

    try {
      const response = await fetch("/api/game/select", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          roundIndex: currentRound,
          eventId,
          targetDate: rounds[currentRound].targetDate,
          allEventIds: rounds[currentRound].events.map(e => e.id)
        }),
      })

      if (!response.ok) throw new Error("提交答案失败")
      
      const { results, correctAnswerId, selectedScore } = await response.json()
      updatedRounds[currentRound].results = results
      updatedRounds[currentRound].correctAnswerId = correctAnswerId
      updatedRounds[currentRound].score = selectedScore
      setRounds(updatedRounds)
      setTotalScore(prev => prev + selectedScore)

      if (currentRound === 9) {
        setGameOver(true)
      } else {
        setTimeout(() => setCurrentRound(prev => prev + 1), 3000)
      }
    } catch (err) {
      setError("无法提交答案")
    }
  }

  const handleRestartGame = () => {
    setGameStarted(false)
    const libraries = librariesParam?.split(",") || []
    startNewGame(libraries)
  }

  if (loading) return <div className="text-center p-8">加载中...</div>
  if (error) return <div className="text-center text-red-500 p-8">{error}</div>

  const round = rounds[currentRound]
  if (!round) return null

  return (
    <div className="max-w-4xl mx-auto p-8">
      <div className="mb-8 flex justify-between items-center">
        <div>
          <span className="text-lg font-semibold">第 {currentRound + 1} 轮</span>
          <span className="ml-4">总分: {totalScore}</span>
        </div>
        <div className="text-lg font-medium">
          目标日期: {new Date(round.targetDate).toLocaleDateString()}
        </div>
      </div>

      <div className="grid gap-4">
        {round.events.map(event => {
          const result = round.results?.find(r => r.eventId === event.id)
          const isSelected = round.selectedEventId === event.id
          const isCorrect = round.correctAnswerId === event.id
          
          return (
            <div
              key={event.id}
              onClick={() => selectEvent(event.id)}
              className={`relative p-4 border rounded-lg cursor-pointer transition-all
                ${!round.selectedEventId ? "hover:border-primary/50" : ""}
                ${round.selectedEventId && isSelected ? "border-primary" : "border-gray-200"}
              `}
            >
              <div className="flex items-center">
                {/* 左侧选择结果标识 */}
                {round.selectedEventId && isSelected && (
                  <span className={`mr-2 text-lg ${isCorrect ? "text-green-600" : "text-red-600"}`}>
                    {isCorrect ? "✓" : "✗"}
                  </span>
                )}
                
                {/* 标题和右侧最佳答案标识 */}
                <div className="flex-grow">
                  <div className="flex items-center justify-between">
                    <h3 className="font-semibold">{event.title}</h3>
                    {round.selectedEventId && isCorrect && (
                      <span className="text-yellow-500 ml-2 text-lg">★</span>
                    )}
                  </div>
                  
                  {event.description && (
                    <p className="text-sm text-gray-600 mt-1">
                      {event.description}
                    </p>
                  )}
                </div>
              </div>

              {round.selectedEventId && result && (
                <div className="mt-2 pt-2 border-t border-gray-200">
                  <p className="text-sm text-gray-600">
                    实际日期: {new Date(event.date).toLocaleDateString()}
                  </p>
                  <p className="text-sm text-gray-600">
                    相差: {result.yearDiff} 年 {result.dayDiff} 天
                  </p>
                  {isSelected && (
                    <p className={`mt-1 font-medium ${
                      isCorrect ? "text-green-600" : "text-red-600"
                    }`}>
                      得分: {result.score}
                    </p>
                  )}
                </div>
              )}
            </div>
          )
        })}
      </div>

      {gameOver && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center">
          <div className="bg-white p-8 rounded-lg text-center">
            <h2 className="text-2xl font-bold mb-4">游戏结束</h2>
            <p className="text-xl mb-4">总分: {totalScore}</p>
            <div className="space-x-4">
              <Button onClick={handleRestartGame}>再玩一次</Button>
              <Button onClick={() => router.push("/game")} variant="outline">
                返回选择
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
} 